<?php

namespace app\api\controller;

use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords;
use app\api\model\Blacklist;
use app\api\model\Dymanic;
use app\api\model\UserClaimAddress;
use app\service\UserIntimate as UserIntimateService;
use think\Db;
use think\Request;

class Nihao extends Common {
    protected $db;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->db = Db::connect('database');
    }
    /**
     * @return mixed
     */
    public function category($auth = 0) {
        // $this->member['id'] = 6;
        if (!$auth) {
            $data = cache('categorynotauth');
            if ($data) {
                return $this->pass($data);
            }
        }
        
        $dy_cate_id = $this->db->name('config_system')->where(['title'=>'dy_cate_id'])->value('content');
        $list = $this->db->name('labels')->where(['is_hidden' => 0, 'user_id'=>['in', [0, $this->member['id']]]])->field('id,name as title,parent_id as tid,icon,service_type')->order('sort desc')->select();
        foreach ($list as &$value) {
            $value['icon'] = $value['icon'] ? _ossUrl(0) . $value['icon'] : '';
        }
        if ($auth) {
            $auths = Db::name('user_attestation')->where(['types'=>['in', [1,2]], 'user_id' => $this->member['id'], 'status'=>1])->column('category');
            $auths = explode(',', implode(',', $auths));
            foreach ($list as &$value) {
                $value['auth'] = in_array($value['id'], $auths);
            }
        }
        $data = $this->toTree($list, $dy_cate_id);
        if (!$auth) {
            cache('categorynotauth', $data, '300');
        } else {
            $data = $this->mergeauthcate($data);
        }
        return $this->pass($data);
    }

    public function createLabel($name = '')
    {
        if (!$name) return $this->miss('请输入标签名称');
        $param = [
            'name'  =>  $name,
            'user_id'=>$this->member['id']
        ];
        $param['id'] = Db::name('topic')->where($param)->value('id');
        if ($param['id']) {
            return $this->pass($param);
        }

        $contain = Db::name('filter_word')->where(['state' => 1])->column('name');
        foreach ($contain as $k => $v) {
            if (stripos($name, $v) !== false) {
                return $this->miss('内容含有敏感词');
            }
        }

        $cachekey = 'createLabel'.$name;
        if ($data = cache($cachekey)) {
            return $this->pass($data);
        }
        
        $param['create_time'] = time();
        $param['id'] = Db::name('topic')->insertGetId($param);
        if ($param['id']) {
            cache($cachekey, $param, 600);
            return $this->pass($param);
        }
        return $this->miss('请重试');
    }

    private function mergeauthcate($data) {
        $case = Db::name('user_attestation')->where(['user_id'=>$this->member['id'], 'status'=>1])->column('category');
        $cate = $this->db->name('labels')->where(['id'=>['in', implode(',', $case)]])->field('id,name title,icon')->select();
        if ($cate) {
            foreach ($cate as &$value) {
                $value['auth'] = true;
                $value['icon'] = $value['icon'] ? _ossUrl(0) . $value['icon'] : '';
            }
            $authed = [
                'id'    => 0,
                'title' => '我的认证',
                'children'=>$cate
            ];
            $data = array_merge([$authed], $data);
        }
        return $data;
    }

    /**
     * @param $category
     * @param $category_pid
     * @return mixed
     */
    private function toTree($category, $category_pid) {
        $tree = [];
        foreach ($category as $v) {
            if ($v['tid'] == $category_pid) {
                $v['children'] = self::toTree($category, $v['id']);
                if ($category_pid) {
                    unset($v['service_type']);
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }

    public function auth($types = 2)
    {
        $timenow = datetime();
        $this->params['user_id'] = $this->member['id'];

        if ($types == 4) {
            $attestation = Db::name('user_attestation')->where([
                'types' => $types,
                'user_id' => $this->params['user_id']
            ])->find();
        } else {
            $attestation = Db::name('user_attestation')->where([
                'types' => $types,
                'user_id' => $this->params['user_id']
            ])->where('find_in_set("'.$this->params['category'].'", category)')->find();
        }

        // 校验身份证
        if (isset($this->params['idcard'])) {
            if (!validateIDCard($this->params['idcard'])) {
                return $this->miss('身份证校验未通过');
            }
            $this->params['birthday'] = _getDateFromIdcard($this->params['idcard']);
        }

        // $cate = $this->db->name('labels')->where(['parent_id'=>['<>', 0], 'is_hidden'=>0, 'id'=>$this->params['category']])->count();
        // if (!$cate) {
        //     return $this->miss('类别选择错误');
        // }

        $this->params['types'] = $types;
        if ($attestation) {
            if ($attestation['status'] == 1) {
                return $this->miss(($types == 4 ? '' : '当前类别') . '已认证');
            } else if ($attestation['status'] == 0) {
                return $this->miss(($types == 4 ? '' : '当前类别') . '认证审核中');
            }
            $this->params['status'] = 0;
            $this->params['reason'] = '';
            $this->params['update_time'] = $timenow;
            $res = Db::name('user_attestation')->where(['id'=>$attestation['id']])->update($this->params);
        } else {
            $this->params['create_time'] = $timenow;
            $res = Db::name('user_attestation')->insert($this->params);
        }
        if ($res) {
            return $this->pass('认证提交成功，待审核');
        }
        return $this->miss('认证提交失败，请稍后再试');
    }

    public function authed($types = 0, $keyword = '')
    {
        $map = ['user_id'=>$this->member['id']];
        if ($types) {
            $map['types'] = $types;
        }
        $case = Db::name('user_attestation')->where($map)->field('id,types,realname,occupation,hospital,category,status,reason,img_a,img_b')->select();
        $cate = Db::name('topic')->where(['id'=>['in', implode(',', array_column($case, 'category'))]])->column('name','id');
        foreach ($case as &$value) {
            $category = explode(',', $value['category']);
            $value['dy_count'] = 0;
            foreach ($category as $k => $v) {
                $value['catename'][] = $cate[$v] ?? '';
                $dy_cate_count = Db::name('dymanic')->where("topic_experience like '&".$cate[$v]."' or topic_experience like '&".$cate[$v]." &%' or topic_experience like '% &".$cate[$v]."' or topic_experience like '% &".$cate[$v]." &%'")->where(['userid'=>$this->member['id'], 'shenhe'=>['in',[0,1]]])->count();
                $value['dy_count'] += $dy_cate_count;
            }
            $value['catename'] = sizeof($value['catename']) ? '#'.implode(' #', $value['catename']) : '';
        }
        return $this->pass($case);
    }


    public function PrePublish()
    {
        $pre = [
            2=>['price'=>[0,10], 'auth'=>1,'name'=>'经验'],
            5=>['price'=>0,'auth'=>1,'name'=>'陷阱']];
        return $this->pass($pre);
    }

    public function publish() {
        $checkDymanic = $this->db->name('config_system')->where(['title' => 'check_dymanic'])->value('content');

        $data       = input('post.');
        $data['class'] = $data['class'] ?? 2;
        if ($data['class'] != 2 && $data['class'] != 5) {
            return $this->miss('类别错误');
        }
        $topic = $data['topic'] ?? '';

        $address_id = $data['address_id'] ?? '';
        $address = $data['address'] ?? '';
        $address_desc = $data['address_desc'] ?? '';
        $longitude = $data['longitude'] ?? '';
        $latitude = $data['latitude'] ?? '';
        $citys = $data['citys'] ?? '';

        $insertKeys = ['category_id', 'title', 'content', 'masterimg', 'video', 'cover', 'community_id', 'class', 'price', 'topic', 'address', 'address_id', 'citys', 'longitude', 'latitude'];
        foreach ($data as $key => $item) {
            if (!in_array($key, $insertKeys)) {
                unset($data[$key]);
                continue;
            }
            $data[$key] = strip_tags($item);
        }
        $data['userid'] = $this->member['id'];

        if (!$data['title']) {
            return $this->miss('请输入标题');
        }
        if (!$data['content']) {
            return $this->miss('请输入内容');
        }
        // $community = $this->db->name('cluster_community')->where(['id' => $data['community_id'], 'state' => 1])->count();
        // if (!$community) {
        //     return $this->miss('请选择小组');
        // }
        
        // $auths = Db::name('user_attestation')->where(['types'=>['in', [1,2,3,4,5]], 'user_id' => $data['userid'], 'status'=>1])->find();
        // if (!$auths) {
        //     return $this->miss('请先完成经验认证');
        // }
        
        if ($data['category_id']) {
            $cate = $this->db->name('labels')->where(['id' => ['in', $data['category_id']], 'parent_id' => ['<>', 0], 'is_hidden' => 0])->field('id,name')->select();
            if (!$cate) {
                return $this->miss('分类不存在');
            }
            // $auths = $this->db->name('user_attestation')->where(['types'=>['in', [1,2]], 'user_id' => $data['userid'], 'status'=>1])->column('category');
            // $auths = explode(',', implode(',', $auths));
            // foreach ($cate as $key => $value) {
            //     if (!in_array($value['id'], $auths)) {
            //         return $this->miss('未认证类别:' . $value['name']);
            //     }
            // }
            
            $data['price'] = isset($data['price']) ? $data['price'] : 0;
            if ($data['class'] == 2 && ($data['price'] < 0 || $data['price'] > 10)) {
                return $this->miss('经验付费阅读价格应在:0~10元');
            }
        } else {
            // return $this->miss('请选择分类');
        }

        $contain = $this->db->name('filter_word')->where(['state' => 1])->column('name');
        foreach ($contain as $k => $v) {
            if (stripos($data['title'], $v) !== false) {
                return $this->miss('标题含有敏感词"' . $v . '",请重新编辑发送');
            }
            if (stripos($data['content'], $v) !== false) {
                return $this->miss('内容含有敏感词"' . $v . '",请重新编辑发送');
            }
        }

        if ($topic) {
            $topic = explode('#', $topic);
            $topics = Db::name('topic')->where(['name'=>['in', $topic]])->column('id', 'name');
            $topics_name = array_keys($topics);
            foreach ($topic as $key => $value) {
                if (!$value) continue;
                if (in_array($value, $topics_name)) {
                    Db::name('topic')->where(['id'=>$topics[$value]])->setInc('count');
                } else {
                    Db::name('topic')->insert(['name'=>$value,'count'=>1,'user_id'=>$this->member['id'], 'create_time'=>time()]);
                }
            }
        }

        if ($address) {
            if (!$address_id) {
                $data['address_id'] = UserClaimAddress::FindByCreate(['name' => $address, 'address' => $address_desc, 'longitude' => $longitude, 'latitude' => $latitude, 'city' => $citys]);
            }
        }

        if ($checkDymanic + 0) {
            $data['shenhe'] = $checkDymanic ? 0 : 1;
            $msg            = '发布成功，待审核通过';
        } else {
            $msg = '发布成功';

            Db::name('user')->where(['id' => $this->member['id']])->setInc('charm_value', 10);
        }

        $masterimg = $data['masterimg'] ?? '';

        if ($masterimg) {
            $masterimg = explode(',', $masterimg);
            $sumbImage = '';
            foreach ($masterimg as $k => $v) {
                $thumb_    = explode('.', $v);
                $thumb1    = $thumb_[0] . '_thumb.' . $thumb_[1];
                $sumbImage = $sumbImage ? $sumbImage . ',' . $thumb1 : $thumb1;
            }
            $data['sumbImage'] = $sumbImage;
        }
        $data['thumbsup'] = 0;
        $data['visit'] = 1;
        $data['addway'] = 2;
        
        $data['liveness'] = _calculateHotScoreNew(1, 0, 0, 0, datetime());

        $insetId = $this->db->name('dymanic')->insertGetId($data);

        if ($insetId) {
            Dymanic::add([
                'userid'      => $this->member['id'],
                'content'     => $data['title'],
                'sumbImage'   => $data['sumbImage'] ?? '',
                'masterimg'   => $data['masterimg'] ?? '',
                'video'   => $data['video'] ?? '',
                'cover'   => $data['cover'] ?? '',
                'longitude'   => $data['longitude'] ?? 0,
                'latitude'   => $data['latitude'] ?? 0,
                'citys'       => $this->member['city'],
                'source_type' => 5,
                'source_id'   => $insetId,
                'shenhe'      => $checkDymanic ? 2 : 1,
                'topic'       => $data['topic'] ?? ''
            ]);
            return $this->pass($msg);
        }
        return $this->miss('发布失败', 201);
    }

    public function posts($keyword = '', $category_id = 0, $page = 1, $pagesize = 20, $self = 0, $class = 2, $topic = '')
    {
        $community_id = 0;
        $user_id = $this->member['id'];
        $map = ['type' => 0, 'shenhe' => 1];
        if ($self) {
            unset($map['shenhe']);
            $map['userid'] = $user_id;
        } else {
            $blacklist = Blacklist::lists($user_id, 1);
            if ($blacklist) {
                $map['userid'] = ['not in', $blacklist];
            }
        }
        $mapOrstr = '';
        if ($community_id) {
            $map['community_id'] = $community_id;
        }
        $map['class'] = $class;
        if ($topic) {
            $map['topic'] = ['like', '%'.$topic.'%'];
        }
        $map2 = [];
        if ($keyword) {
            $category = $this->db->name('labels')->where(['name'=>$keyword])->value('id');
            if ($category && !$category_id) {
                $map2 = $map;
                $map2['category_id'] = $category;
            }
            $map['title|content'] = ['like', '%'.$keyword.'%'];
        }
        $offset = 0;
        $order = 'addtime desc, sort desc, dy_id desc';
        if ($category_id) {
            $category_ids = $this->db->name('labels')->where(['parent_id'=>$category_id])->cache(60)->column('id');
            array_push($category_ids, (int)$category_id);
            $map['category_id'] = ['in', $category_ids];
        } else {
            $dy_cate_id = $this->db->name('config_system')->where(['title'=>'dy_cate_id'])->value('content');
            $category_ids_1 = $this->db->name('labels')->where(['parent_id'=>$dy_cate_id])->cache(60)->column('id');
            $category_ids_2 = $this->db->name('labels')->where(['parent_id'=>['in', $category_ids_1]])->cache(60)->column('id');
            $map['category_id'] = ['in', array_merge($category_ids_1, $category_ids_2)];
            $order = 'liveness desc, dy_id desc';
            if ($topic) {
                $offset = 0;
            } else if ($page == 1) {
                $offset = rand(0, 30);
                cache('postsrecommend' . $this->member['id'], $offset);
            } else {
                $offset = cache('postsrecommend' . $this->member['id']) ?? 0;
            }
        }

        // 获取两个库的用户锚点
        // if ($this->member) {
        //     if (strtotime($this->member['register_datetime']) > strtotime('2023-04-15')) {
        //         $auid = Db::name('user')->where(['register_datetime'=>['>=', '2023-04-15']])->value('id');
        //         if ($auid) {
        //             $buid = $this->db->name('user')->where(['register_datetime'=>['>=', '2023-04-15']])->value('id');
        //             $mapOrstr = "(userid >= $auid and userid < 30000000) or userid >= $buid";
        //         } else {
        //             $auid = Db::name('user')->where(['register_datetime'=>['<', '2023-04-15']])->order('id desc')->value('id');
        //             $buid = $this->db->name('user')->where(['register_datetime'=>['<', '2023-04-15']])->order('id desc')->value('id');
        //             $mapOrstr = "(userid <= $buid and userid > 30000000) or userid <= $auid";
        //         }
        //     }
        // }
        $field = 'dy_id,type,category_id,userid,title,content,addway,sumbImage,masterimg,video,cover,thumbsup,comments,addtime,community_id,class,comment_time,shenhe,price,topic';
        if (sizeof($map2)) {
            $data = $this->db->name('dymanic')
                ->field($field)
                ->where($map)
                ->where($mapOrstr)
                ->whereOr(function ($query) use ($mapOrstr, $map2) {
                    $query->where($map2)->where($mapOrstr);
                })
                ->limit(($page - 1) * $pagesize + $offset, $pagesize)
                // ->fetchSql(true)
                ->order($order)
                ->select();
            $count = $this->db->name('dymanic')
                ->where($map)
                ->where($mapOrstr)
                ->whereOr(function ($query) use ($mapOrstr, $map2) {
                    $query->where($map2)->where($mapOrstr);
                })
                ->count();
        // var_dump($data);exit;
        } else {
            $data = $this->db->name('dymanic')
                ->field($field)
                ->where($map)
                ->where($mapOrstr)
                ->limit(($page - 1) * $pagesize + $offset, $pagesize)
                ->order($order)
                // ->fetchSql(true)
                ->select();
            $count = $this->db->name('dymanic')
                ->where($map)
                ->where($mapOrstr)
                ->count();
        // var_dump($data);exit;
        }
        $count = $count - $offset;
        $reloadposts = cache('reloadposts') ?? 0;
        if ($offset && $count <= 0 && $page == 1 && $reloadposts < 3) {
            cache('reloadposts', ++$reloadposts, 10);
            return $this->posts($keyword, $category_id, $page, $pagesize, $self, $class, $topic);
        }
        $thumbsups = $this->db->name('dymanic_userthumbsup')->where(['userid' => $user_id, 'dy_id' => ['in', array_column($data, 'dy_id')]])->column('dy_id');
        $user_a = [];
        $user_b = [];
        $users = [];
        foreach ($data as $value) {
            if ($value['userid'] > 30000000) {
                $user_a[] = $value['userid'];
            } else {
                $user_b[] = $value['userid'];
            }
        }
        
        $user_a = $this->db->name('user')->where(['id' => ['in', $user_a]])->column('id,name,head_portrait');
        $user_b = Db::name('user')->where(['id' => ['in', $user_b]])->column('id,name,head_portrait');
        $userstmp = array_merge($user_a, $user_b);
        foreach ($userstmp as &$value) {
            $value['head_portrait'] = _ossUrl($value['id'] > 30000000 ? 0 : 1) . $value['head_portrait'];
            $users[$value['id']] = $value;
        }
        $app_rate = getenv('APP_RATE');
        foreach ($data as &$value) {
            if ($value['comment_time']) {
                $value['comment_time'] = _time($value['comment_time']);
            }
            $value['price'] *= $app_rate;
            $value['addtime'] = _time(strtotime($value['addtime']));
            $value['user']    = $users[$value['userid']] ?? false;
            if ($value['masterimg']) {
                $value['masterimg'] = explode(',', $value['masterimg']);
                foreach ($value['masterimg'] as &$v) {
                    $v = _ossUrl($value['addway'] > 1 ? 1 : 0) . $v;
                }
                $value['sumbImage'] = explode(',', $value['sumbImage']);
                foreach ($value['sumbImage'] as &$v) {
                    $v = _ossUrl($value['addway'] > 1 ? 1 : 0) . $v;
                }
            } else if (!$value['cover']) {
                $doc=new \DOMDocument('1.0', 'utf-8');
                $internalErrors = libxml_use_internal_errors(true);
                $doc->loadHTML($value['content']);
                libxml_use_internal_errors($internalErrors);
                $xpath = new \DOMXPath($doc);

                // 使用 XPath 查询所有图像元素
                $images = $xpath->query('//img');

                // 遍历图像元素并获取 src 属性值
                $value['masterimg'] = [];
                $value['sumbImage'] = [];
                foreach ($images as $image) {
                    $src = $image->getAttribute('src');
                    if (strpos($src, "http://") === false && strpos($src, "https://") === false) {
                        $src = str_replace('/disk/uploads/download/', _ossUrl(0) . '/disk/uploads/download/', $src);
                        $src = str_replace('/public/uploads/us', 'http://nihao.meiyue.co/public/uploads/us', $src);
                    }
                    $value['masterimg'][] = $src;
                    $value['sumbImage'][] = $src;
                }
            }
            $value['video'] = $value['video'] ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $value['video'] : '';
            $value['cover'] = $value['cover'] ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $value['cover'] : '';
            $value['isthumbsup'] = in_array($value['dy_id'], $thumbsups) ? 1 : 0;

            // if ($value['class'] == '2') {
                $auth_tags = Db::name('user_attestation')->where(['user_id'=>$value['userid'], 'types'=>2,'status'=>1])->column('category');
                $auth_tags = $this->db->name('labels')->where(['id'=>['in', implode(',',$auth_tags)]])->column('name');
                $value['auth_tags'] = $auth_tags;
            // }
            $value['auths'] = Db::name('user_attestation')->where(['user_id'=>$value['userid'], 'status'=>1, ['exp', Db::raw('find_in_set('.$value['category_id'].', category)')]])->field('category,hospital,types,occupation')->select();

            if ($value['content']) {
                $value['content'] = strip_tags(htmlspecialchars_decode($value['content']));
                $value['content'] = str_replace('\n', '', $value['content']);
                $value['content'] = str_replace('\r', '', $value['content']);
                $value['content'] = str_replace(' ', '', $value['content']);
                $value['content'] = preg_replace('/\s+/','', $value['content']);
                $value['content'] = mb_substr($value['content'], 0, 100);
            }

            if ($value['topic']) {
                $topic = explode('#',$value['topic']);
                $value['topic'] = [];
                foreach ($topic as &$v) {
                    if ($v) $value['topic'][] = $v;
                }
            } else {
                $value['topic'] = [];
            }
        }

        return $this->pass($data, 'data', ['count'=>$count]);
    }
    public function dele($id)
    {
        $user_id = $this->member['id'];
        $dy = $this->db->name('dymanic')->where(['dy_id'=>$id])->find();
        $del = false;
        if ($dy['userid'] == $user_id) {
            $del = $this->db->name('dymanic')->where(['dy_id'=>$id])->delete();
        }
        if ($del) {
            return $this->pass('已删除');
        }
        return $this->miss('操作失败');
    }
    public function info($dy_id) {
        $userid = $this->member['id'];

        //查询动态
        $data = $this->db->name('dymanic')
            ->where(['dy_id' => $dy_id])
            ->field('dy_id,type,userid,title,content,addway,addtime,thumbsup,visit,comments,shares,addtime,sumbImage,masterimg,video,cover,community_id,class,category_id,shenhe,price,source_id,topic')
            ->find();

        if (!$data) {
            return $this->miss('内容飞走了~');
        }
        if ($data['shenhe'] != 1 && $data['userid'] != $userid) {
            return $this->miss('内容飞走了~');
        }

        if ($data['userid'] > 30000000) {
            $user = $this->db->name('user')->where(['id'=>$data['userid'], 'delete_time' => 0])->field('name,head_portrait,sex,age')->find();
        } else {
            $user = Db::name('user')->where(['id'=>$data['userid'], 'delete_time' => 0])->field('name,head_portrait,sex,age')->find();
        }
        if (!$user) {
            // return $this->miss('内容飞走了~');
        } else {
            $user['head_portrait'] = _ossUrl($data['userid'] > 30000000 ? 0 : 1) . $user['head_portrait'];
            $data = array_merge($data, $user);
        }

        //查询是否点赞和喜欢
        $thumbsup           = $this->db->name('dymanic_userthumbsup')->where(['userid' => $userid, 'dy_id' => $dy_id])->count();
        $data['isthumbsup'] = $thumbsup ? 1 : 0;
        if ($data['masterimg']) {
            $data['masterimg']  = explode(",", $data['masterimg']);
            $data['sumbImage']  = explode(",", $data['sumbImage']);
            foreach ($data['masterimg'] as &$v) {
                $v = _ossUrl($data['addway'] > 1 ? 1 : 0) . $v;
            }
            foreach ($data['sumbImage'] as &$v) {
                $v = _ossUrl($data['addway'] > 1 ? 1 : 0) . $v;
            }
        }
        $data['video'] = $data['video'] ? _ossUrl($data['addway'] > 1 ? 1 : 0) . $data['video'] : '';
        $data['cover'] = $data['cover'] ? _ossUrl($data['addway'] > 1 ? 1 : 0) . $data['cover'] : '';
        $data['category_second_name'] = '';
        $data['category_first_name'] = '';
        if ($data['category_id']) {
            $category_second = $this->db->name('labels')->where(['id'=>$data['category_id']])->find();
            $data['category_second_name'] = $category_second['name'];
            $data['category_first_name'] = $this->db->name('labels')->where(['id'=>$category_second['parent_id']])->value('name');
        }

        if (!cache('dyinfo:'. $userid . ':dyid' . $dy_id)) {
            $this->db->name('dymanic')
                ->where(['dy_id' => $dy_id])
                ->update([
                    'visit'  =>  $this->db->raw('visit+1'),
                    // 'liveness'  =>  _calculateHotScore(++$data['visit'], $data['comments'], $data['thumbsup'], $data['shares'])
                ]);
            cache('dyinfo:'. $userid . ':dyid' . $dy_id, $dy_id, 10);


            $hasRead = Db::name('dymanic_read')->where(['dy_id'=>$dy_id, 'userid'=>$userid])->find();
            if ($hasRead) {
                Db::name('dymanic_read')->where(['id'=>$hasRead['id']])->update(['time'=>date('Y-m-d H:i:s')]);
            } else {
                Db::name('dymanic_read')->insert(['dy_id'=>$dy_id, 'userid'=>$userid]);
            }

            Db::name('user')->where(['id' => $data['userid']])->setInc('charm_value', 0.01);
        }
        if ($data['content']) {
            $data['content'] = str_replace('/disk/uploads/download/', _ossUrl(0) . '/disk/uploads/download/', $data['content']);
            $data['content'] = str_replace('<img ', '<img style="max-width:90vw;" ', $data['content']);
                    
            // if ($data['source_id'] > 0) {
                // 匹配style属性
                $pattern = '/style="[^"]*"/i';
                // 将style属性替换为空
                $data['content'] = preg_replace($pattern, '', $data['content']);
            // }

            $data['content'] = str_replace('src="/public', 'style="max-width:90vw;" src="http://nihao.meiyue.co/public', $data['content']);
            $data['content'] = preg_replace('/(width|height)\s*=\s*"\d*"\s*/i', '', $data['content']);
            $data['tips'] = '<div style="font-weight:bold;font-size:15px;padding:20px;background:#f6f6f6;"><p style="margin-bottom:6px">温馨提示：</p>去认证经验，就可以发布付费经验，陷阱得到可观的报酬，还可以设置付费聊天，让想美丽的用户的用户付费向你咨询。</div>';
        }

        $data['islover'] = $this->db->name('dymanic_userlover')->where(['userid'=>$this->member['id'], 'dy_id'=>$dy_id])->count();

        $data['price'] *= getenv('APP_RATE');
        if ($data['class'] == 2 && $data['userid'] != $this->member['id']) {
            $data['paystate'] = $this->db->name('order_of_subscribe')->where(['user_id'=>$this->member['id'], 'dy_id'=>$dy_id])->count();
        } else {
            $data['paystate'] = 1;
        }
        // if ($data['class'] == '2') {
            $auth_tags = Db::name('user_attestation')->where(['user_id'=>$data['userid'], 'types'=>2,'status'=>1])->column('category');
            $auth_tags = $this->db->name('labels')->where(['id'=>['in', implode(',',$auth_tags)]])->column('name');
            $data['auth_tags'] = $auth_tags;
        // }
            $data['auths'] = Db::name('user_attestation')->where(['user_id'=>$data['userid'], 'status'=>1, ['exp', Db::raw('find_in_set('.$data['category_id'].', category)')]])->field('category,hospital,types,occupation')->select();

        if ($data['topic']) {
            $topic = explode('#',$data['topic']);
            $data['topic'] = [];
            foreach ($topic as &$v) {
                if ($v) $data['topic'][] = $v;
            }
        } else {
            $data['topic'] = [];
        }

        return $this->pass($data);
    }

    public function subscribe($dy_id)
    {
        $article = $this->db->name('dymanic')->where(['dy_id'=>$dy_id, 'shenhe'=>1, 'class'=>2])->find();
        if (!$article) {
            return $this->pass('内容飞走了');
        }
        if ($article['userid'] == $this->member['id']){
            return $this->pass('错误操作');
        }

        $paystate = $this->db->name('order_of_subscribe')->where(['user_id'=>$this->member['id'], 'dy_id'=>$dy_id])->count();
        if ($paystate) {
            return $this->pass('已支付');
        }
        $timenow = time();
        // 支付
        $total = getenv('APP_RATE') * $article['price'];
        // 兑换成收款方对应汇率积分
        $toScore = $article['userid'] > 30000000 ? getenv('APP_RATE_NIHAO') * $article['price'] : $total;
        $rate = $this->db->name('config_system')->where(['title'=>'fencheng_user'])->value('content');
        $content = '订阅文章';
        $number = uniqid('sub');
        $orders = [
            'user_id' => $this->member['id'],
            'touserid' => $article['userid'],
            'order_sn'  => $number,
            'totalprice' => $toScore,
            'rate' => $rate,
            'price' => $toScore * $rate,
            'dy_id' => $article['dy_id'],
            'dy_title' => $article['title'],
            'time' => $timenow
        ];

        if ($this->member['volley'] < $total) {
            return $this->miss('账户余额不足', 507);
        }

        if ($article['userid'] > 30000000) {
            $touser = $this->db->name('user')->where(['id'=>$article['userid']])->field('id,score')->find();
        } else {
            $touser = Db::name('user')->where(['id'=>$article['userid']])->field('id,score')->find();
        }

        // 启动事务
        $this->db->startTrans();
        try {
            $BalanceState = Balance::index($this->member['id'], $total, $content . ' no.' . $number);

            $insert = $this->db->name('order_of_subscribe')->insertGetId($orders);
            $orders['id'] = $insert;

            if ($touser['id'] > 30000000) {
                $this->db->name('user')->where(['id' => $article['userid']])->setInc('score', $orders['price']);
                $current_balance = $touser['score'] + $orders['price'];
                $IncomeState = $this->db->name('yaoqing_records')->insert([
                    'uid' => $article['userid'],
                    'touid' => $this->member['id'],
                    'content' => '经验文章 「'.$article['title'].'」 收益',
                    'money' => $orders['price'],
                    'type' => 1,
                    'data' => 0,
                    'order_id' => $insert,
                    'balance' => $current_balance,
                    'time' => time()
                ]);
            } else {
                $IncomeState = YaoqingRecords::index($article['userid'], $this->member['id'], $orders['price'], '经验文章 「'.$article['title'].'」 收益', 1, $insert);
            }

            $orders['toScore'] = $toScore;
            $this->db->name('order_common')->insert([
                'types' => 8,
                'number'=> $number,
                'user_id'=>$this->member['id'],
                'money' => $total,
                'data'  => json_encode($orders, JSON_UNESCAPED_UNICODE),
                'pays'  => 1,
                'status'=> 1,
                'create_time'=>$timenow,
                'update_time'=>$timenow
            ]);

            if($BalanceState && $IncomeState && $insert){
                // 提交事务
                $this->db->commit();
            }else{
                throw new \think\Exception('订阅文章异常，请重试', 100010);
            }
        } catch (\Exception $e) {
            // 回滚事务
            $this->db->rollback();

            return $this->miss($e->getMessage());
        }

        return $this->pass('支付成功');
    }
    public function thumbsup($id, $status = 1)
    {
        $user_id = $this->member['id'];
        $result = false;
        $dymanic = $this->db->name('dymanic')->where(['dy_id'=>$id])->find();
        $thumbsup = $this->db->name('dymanic_userthumbsup')->where(['dy_id' => $id, 'userid' => $user_id])->count();
        switch ((int)$status) {
            case 1:
                if ($thumbsup) {
                    return $this->pass("点赞成功");
                }
                $code = $this->db->name('dymanic')
                            ->where(['dy_id'=>$id])
                            ->update([
                                'thumbsup'  =>  Db::raw('thumbsup+1'),
                                // 'liveness'  =>  _calculateHotScore($dymanic['visit'], $dymanic['comments'], ++$dymanic['thumbsup'], $dymanic['shares'])
                            ]);
                $this->db->name('dymanic_userthumbsup')->insert(['userid'=>$user_id, 'dy_id'=>$id]);
                if ($code) {
                    if ($dymanic['userid'] < 30000000) {
                        Db::name('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 1);
                        $locDymanic = Db::name('dymanic')->where(['userid'=>$dymanic['userid'], 'source_type'=>5, 'source_id'=>$id])->value('dy_id');
                        if ($locDymanic) {
                            Db::name('user')->name('dymanic_userthumbsup')->insert(['userid'=>$dymanic['userid'], 'dy_id'=>$locDymanic]);
                            Db::name('user')->name('dymanic')->where(['dy_id'=>$locDymanic])->setInc('thumbsup');
                        }
                    }
                    $result = true;
                }
                break;
            case 2:
                if (!$thumbsup) {
                    return $this->pass('已取消');
                }
                $code = $this->db->name('dymanic')
                            ->where(['dy_id'=>$id])
                            ->update([
                                'thumbsup'  =>  Db::raw('thumbsup+1'),
                                // 'liveness'  =>  _calculateHotScore($dymanic['visit'], $dymanic['comments'], ++$dymanic['thumbsup'], $dymanic['shares'])
                            ]);
                $this->db->name('dymanic_userthumbsup')->where(['userid'=>$user_id, 'dy_id'=>$id])->delete();
                if ($code) {
                    if ($dymanic['userid'] < 30000000) {
                        Db::name('user')->where(['id' => $dymanic['userid']])->setDec('charm_value', 1);
                        $locDymanic = Db::name('dymanic')->where(['userid'=>$dymanic['userid'], 'source_type'=>5, 'source_id'=>$id])->value('dy_id');
                        if ($locDymanic) {
                            Db::name('user')->name('dymanic_userthumbsup')->where(['userid'=>$dymanic['userid'], 'dy_id'=>$locDymanic])->delete();
                            Db::name('user')->name('dymanic')->where(['dy_id'=>$locDymanic])->setDec('thumbsup');
                        }
                    }
                    $result = true;
                }
            default:
                break;
        }
        return $result ? $this->pass($status==1?'点赞成功':'已取消点赞') : $this->miss($status?'点赞失败':'取消点赞失败');
    }
    public function order($page = 1, $pagesize = 20)
    {
        $user_id = $this->member['id'];
        $data = $this->db->name('order_of_subscribe')
                    ->alias('a')
                    ->join('dymanic b', 'b.dy_id=a.dy_id')
                    ->where([
                        'a.user_id'=>$user_id,
                        'b.shenhe'=>1
                    ])
                    ->field('b.dy_id,b.type,b.userid,b.title,b.category_id,b.addway,b.content,b.sumbImage,b.masterimg,b.video,b.cover,b.thumbsup,b.comments,b.addtime,b.community_id,b.class,b.comment_time,b.shenhe')
                    ->page($page)
                    ->limit($pagesize)
                    ->order('id desc')
                    ->select();
        $thumbsups = $this->db->name('dymanic_userthumbsup')->where(['userid' => $user_id, 'dy_id' => ['in', array_column($data, 'dy_id')]])->column('dy_id');
        $user_a = [];
        $user_b = [];
        $users = [];
        foreach ($data as $value) {
            if ($value['userid'] > 30000000) {
                $user_a[] = $value['userid'];
            } else {
                $user_b[] = $value['userid'];
            }
        }
        $user_a = $this->db->name('user')->where(['id' => ['in', $user_a]])->column('id,name,head_portrait');
        $user_b = Db::name('user')->where(['id' => ['in', $user_b]])->column('id,name,head_portrait');
        $userstmp = array_merge($user_a, $user_b);
        foreach ($userstmp as &$value) {
            $value['head_portrait'] = _ossUrl($value['id'] > 30000000 ? 0 : 1) . $value['head_portrait'];
            $users[$value['id']] = $value;
        }
        foreach ($data as &$value) {
            if ($value['comment_time']) {
                $value['comment_time'] = _time($value['comment_time']);
            }
            $value['addtime'] = _time(strtotime($value['addtime']));
            $value['user']    = $users[$value['userid']] ?? false;
            $value['masterimg'] = explode(',', $value['masterimg']);
            $value['sumbImage'] = explode(',', $value['sumbImage']);
            foreach ($value['masterimg'] as &$v) {
                $v = _ossUrl($value['addway'] > 1 ? 1 : 0) . $v;
            }
            foreach ($value['sumbImage'] as &$v) {
                $v = _ossUrl($value['addway'] > 1 ? 1 : 0) . $v;
            }
            $value['video'] = $value['video'] ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $value['video'] : '';
            $value['cover'] = $value['cover'] ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $value['cover'] : '';
            $value['isthumbsup'] = in_array($value['dy_id'], $thumbsups) ? 1 : 0;
            // if ($value['class'] == '2') {
                $auth_tags = Db::name('user_attestation')->where(['user_id'=>$value['userid'], 'types'=>2,'status'=>1])->column('category');
                $auth_tags = $this->db->name('labels')->where(['id'=>['in', implode(',',$auth_tags)]])->column('name');
                $value['auth_tags'] = $auth_tags;
            // }
            $value['auths'] = Db::name('user_attestation')->where(['user_id'=>$value['userid'], 'status'=>1, ['exp', Db::raw('find_in_set('.$value['category_id'].', category)')]])->field('category,hospital,types,occupation')->select();
        }

        return $this->pass($data);
    }




    public function lover($type = 1, $dy_id)
    {
        $userid = $this->member['id'];

        $dymanic = $this->db->name('dymanic')->where(['dy_id'=>$dy_id])->find();
        switch ($type) {
            case 1:
                $has = $this->db->name('dymanic_userlover')->where(['userid'=>$userid, 'dy_id'=>$dy_id])->count();
                if ($has) {
                    return $this->pass('已收藏');
                }
                $res = $this->db->name('dymanic_userlover')->insert(['userid'=>$userid, 'dy_id'=>$dy_id, 'time'=>time()]);
                if ($res) {
                    $this->db->name('dymanic')->where(['dy_id'=>$dy_id])->setInc('lover');

                    if ($dymanic['userid'] < 30000000) {
                        Db::name('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 5);
                        $locDymanic = Db::name('dymanic')->where(['userid'=>$dymanic['userid'], 'source_type'=>5, 'source_id'=>$dy_id])->value('dy_id');
                        if ($locDymanic) {
                            Db::name('user')->name('dymanic_userlover')->insert(['userid'=>$userid, 'dy_id'=>$locDymanic, 'time'=>time()]);
                            Db::name('user')->name('dymanic')->where(['dy_id'=>$locDymanic])->setInc('lover');
                        }
                    }
                    return $this->pass('收藏成功');
                }
                return $this->miss('收藏失败');
                break;
            case 2:
                $res = $this->db->name('dymanic_userlover')->where(['userid'=>$userid, 'dy_id'=>$dy_id])->delete();
                if ($res) {
                    $this->db->name('dymanic')->where(['dy_id'=>$dy_id])->setDec('lover');


                    if ($dymanic['userid'] < 30000000) {
                        Db::name('user')->where(['id' => $dymanic['userid']])->setDec('charm_value', 5);
                        $locDymanic = Db::name('dymanic')->where(['userid'=>$dymanic['userid'], 'source_type'=>5, 'source_id'=>$dy_id])->value('dy_id');
                        if ($locDymanic) {
                            Db::name('user')->name('dymanic_userlover')->where(['userid'=>$userid, 'dy_id'=>$locDymanic])->delete();
                            Db::name('user')->name('dymanic')->where(['dy_id'=>$locDymanic])->setDec('lover');
                        }
                    }
                    return $this->pass('取消收藏成功');
                }
                return $this->miss('取消收藏失败');
            default:
                return $this->miss('操作错误');
                break;
        }
    }

    public function collection($page = 1, $pagesize = 20)
    {
        $user_id = $this->member['id'];
        $data = $this->db->name('dymanic_userlover')
                    ->alias('a')
                    ->join('dymanic b', 'b.dy_id=a.dy_id')
                    ->where([
                        'a.userid'=>$user_id,
                        'b.shenhe'=>1
                    ])
                    ->field('b.dy_id,b.type,b.userid,b.title,b.category_id,b.addway,b.content,b.sumbImage,b.masterimg,b.video,b.cover,b.thumbsup,b.comments,b.addtime,b.community_id,b.class,b.comment_time,b.shenhe')
                    ->page($page)
                    ->limit($pagesize)
                    ->order('a.time desc')
                    ->select();
        $thumbsups = $this->db->name('dymanic_userthumbsup')->where(['userid' => $user_id, 'dy_id' => ['in', array_column($data, 'dy_id')]])->column('dy_id');

        $user_a = [];
        $user_b = [];
        $users = [];
        foreach ($data as $value) {
            if ($value['userid'] > 30000000) {
                $user_a[] = $value['userid'];
            } else {
                $user_b[] = $value['userid'];
            }
        }

        $user_a = $this->db->name('user')->where(['id' => ['in', $user_a]])->column('id,name,head_portrait');
        $user_b = Db::name('user')->where(['id' => ['in', $user_b]])->column('id,name,head_portrait');
        $userstmp = array_merge($user_a, $user_b);
        foreach ($userstmp as &$value) {
            $value['head_portrait'] = _ossUrl($value['id'] > 30000000 ? 0 : 1) . $value['head_portrait'];
            $users[$value['id']] = $value;
        }

        $communitys = $this->db->name('cluster_community')->where(['id'=>['in', array_unique(array_column($data, 'community_id'))]])->column('name,image', 'id');
        foreach ($data as &$value) {
            if ($value['comment_time']) {
                $value['comment_time'] = _time($value['comment_time']);
            }
            $value['addtime'] = _time(strtotime($value['addtime']));
            $value['user']    = $users[$value['userid']] ?? false;
            $value['masterimg'] = explode(',', $value['masterimg']);
            $value['masterimg'] = array_filter($value['masterimg'], function ($v) {
                return !is_null($v) && !empty($v);
            });
            $value['sumbImage'] = explode(',', $value['sumbImage']);
            $value['sumbImage'] = array_filter($value['sumbImage'], function ($v) {
                return !is_null($v) && !empty($v);
            });
            foreach ($value['masterimg'] as &$v) {
                $v = $v ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $v : '';
            }
            foreach ($value['sumbImage'] as &$v) {
                $v = $v ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $v : '';
            }
            $value['video'] = $value['video'] ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $value['video'] : '';
            $value['cover'] = $value['cover'] ? _ossUrl($value['addway'] > 1 ? 1 : 0) . $value['cover'] : '';
            $value['community'] = $communitys[$value['community_id']] ?? false;
            $value['isthumbsup'] = in_array($value['dy_id'], $thumbsups) ? 1 : 0;
            // if ($value['class'] == '2') {
                $auth_tags = Db::name('user_attestation')->where(['user_id'=>$value['userid'], 'types'=>2,'status'=>1])->column('category');
                $auth_tags = $this->db->name('labels')->where(['id'=>['in', implode(',',$auth_tags)]])->column('name');
                $value['auth_tags'] = $auth_tags;
            // }

            $value['auths'] = Db::name('user_attestation')->where(['user_id'=>$value['userid'], 'status'=>1, ['exp', Db::raw('find_in_set('.$value['category_id'].', category)')]])->field('category,hospital,types,occupation')->select();
        }

        return $this->pass($data);
    }


    public function comment($dy_id, $content = '', $touserid = 0, $pid = 0, $at = '') {
        $checkDymanic = $this->db->name('config_system')->where(['title' => 'chekc_dycomment'])->value('content');
        $userid       = $this->member['id'];
        $type         = $pid ? 1 : 0;

        $content = strip_tags($content);
        if (ishasPhoneNumber($content)) {
            return $this->miss('禁止发送手机号');
        }

        $contain = $this->db->name('filter_word')->where(['state' => 1])->column('name');
        foreach ($contain as $k => $v) {
            if (stripos($content, $v) !== false) {
                return $this->miss('消息含有敏感词"' . $v . '",请重新编辑发送');
            }
        }

        $Dymanic = $this->db->name('dymanic')->where(['dy_id' => $dy_id, 'shenhe' => 1])->find();
        if (!$Dymanic) {
            return $this->miss('动态不存在');
        }

        if ($pid == 0) {
            $touserid = 0;
        }

        $insertArr = [
            "dy_id"    => $dy_id,
            "content"  => $content,
            "userid"   => $userid,
            "touserid" => $touserid,
            "type"     => $type,
            "shenhe"   => $checkDymanic == 0 ? 1 : 0,
            "pid"      => $pid,
        ];

        $res = $this->db->name('dycomment')->insertGetId($insertArr);
        if (!$res) {
            return $this->miss('系统错误');
        }

        if ($checkDymanic + 0) {
            $data['shenhe'] = $checkDymanic ? 0 : 1;
            $msg            = '评论成功，待审核通过';
        } else {
            if (!$type) {
                $this->db->name('dymanic')->where(['dy_id' => $dy_id])->update([
                    'comments'     => Db::raw('comments+1'),
                    'comment_time' => time(),
                    // 'liveness'  =>  _calculateHotScore($Dymanic['visit'], ++$Dymanic['comments'], $Dymanic['thumbsup'], $Dymanic['shares'])
                ]);

                Db::name('user')->where(['id' => $Dymanic['userid']])->setInc('charm_value', 2);
            }
            $msg = '评论成功';


            $messages = [];
            if ($userid != $Dymanic['userid']) {
                $messages[] = [
                    'type' => 17,
                    'to_user' => $Dymanic['userid'],
                    'context' => json_encode([
                                    'name' => $this->member['name'],
                                    'head' => $this->member['head_100'],
                                    'content' => $content,
                                    'dy_id' => $dy_id,
                                    'pid'   => $pid,
                                    'comment_id' => $res
                                ], JSON_UNESCAPED_UNICODE),
                    'uid' => $this->member['id'],
                    'user_id' => $res //评论id
                ];
            }

            if ($touserid && $touserid != $userid) {
                $messages[] = [
                    'type' => 18,
                    'to_user' => $touserid,
                    'context' => json_encode([
                                    'name' => $this->member['name'],
                                    'head' => $this->member['head_100'],
                                    'content' => $content,
                                    'dy_id' => $dy_id,
                                    'pid'   => $pid,
                                    'comment_id' => $res
                                ], JSON_UNESCAPED_UNICODE),
                    'uid' => $this->member['id'],
                    'user_id' => $res //评论id
                ];
            } else if ($pid) {
                $pinfo = $this->db->name('dycomment')->where(['comment_id'=>$pid])->find();
                if ($userid != $pinfo['userid'] && $pinfo['userid'] != $Dymanic['userid']) {
                    $messages[] = [
                        'type' => 17,
                        'to_user' => $pinfo['userid'],
                        'context' => json_encode([
                                        'name' => $this->member['name'],
                                        'head' => $this->member['head_100'],
                                        'content' => $content,
                                        'dy_id' => $dy_id,
                                        'pid'   => $pid,
                                        'comment_id' => $res
                                    ], JSON_UNESCAPED_UNICODE),
                        'uid' => $this->member['id'],
                        'user_id' => $res //评论id
                    ];
                }
            }
            $this->db->name('sys_message')->insertAll($messages);
        }

        return $this->pass($msg);
    }

    public function comments($dy_id = 0, $pid = 0, $page = 1, $pagesize = 10, $returnJson = true) {
        $data = $this->db->name('dycomment')
            ->field("comment_id,content,touserid,addtime,best,at,userid")
            ->where(['dy_id' => $dy_id, 'shenhe' => 1, 'pid' => $pid])
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('addtime desc')
            ->select();

        $uids = explode(',', implode(',', array_filter(array_unique(array_column($data, 'touserid')))));
        $uids = array_filter(array_unique(array_merge(array_column($data, 'userid'), $uids)));
        $users     = [];
        if ($uids) {
            $user_a = [];
            $user_b = [];
            $users = [];
            foreach ($uids as $value) {
                if ($value > 30000000) {
                    $user_a[] = $value;
                } else {
                    $user_b[] = $value;
                }
            }
            $user_a = $this->db->name('user')->where(['id' => ['in', $user_a]])->column('id,name,head_portrait');
            $user_b = Db::name('user')->where(['id' => ['in', $user_b]])->column('id,name,head_portrait');
            $userstmp = array_merge($user_a, $user_b);
            foreach ($userstmp as &$value) {
                $value['head_portrait'] = _ossUrl($value['id'] > 30000000 ? 0 : 1) . $value['head_portrait'];
                $users[$value['id']] = $value;
            }
        }
        $article = $this->db->name('dymanic')->where(['dy_id'=>$dy_id])->field('dy_id,userid,class')->find();

        foreach ($data as &$value) {
            $value['addtime'] = _time(strtotime($value['addtime']));
            // 如果存在@对象
            $value['at'] = self::atDecode($value['at']);

            if (isset($users[$value['userid']])) {
                $value = array_merge($value, $users[$value['userid']]);
            }

            // 是否顶层
            if ($pid == 0) {
                // 层内评论总数
                $value['nextcount'] = $this->db->name('dycomment')->where(['dy_id' => $dy_id, 'pid' => $value['comment_id']])->count();
                $value['childs']    = $this->comments($dy_id, $value['comment_id'], 1, 3, false);
            } else {
                // 层内回复对象
                if ($value['touserid'] && isset($users[$value['touserid']])) {
                    $value['touser'] = ['id' => $value['touserid'], 'name' => $users[$value['touserid']]['name']];
                }
            }
            if ($article['class'] == 4) {
                $value['price'] = 1 * $app_rate;
                $value['paystate'] = in_array($value['comment_id'], $boughts) || $value['id'] == $this->member['id'] || $article['userid'] == $this->member['id'];
            }
        }
        return $returnJson ? $this->pass($data) : $data;
    }
    public static function atDecode($at)
    {
        $data = [];
        if ($at) {
            try {
                $at = json_decode($at, true);
                foreach ($at as $key => $value) {
                    $data[] = ['id'=>$key, 'name'=>$value];
                }
            } catch (\Exception $e) {
            }
        }
        return $data;
    }
    public function rmvisit($dy_id)
    {
        $res = $this->db->name('dymanic_read')->where(['dy_id'=>$dy_id, 'userid'=>$this->member['id']])->delete();
        return $res ? $this->pass('删除成功') : $this->miss('删除失败');
    }
    public function cleardata($type = 0)
    {
        $tables = ['dymanic_read', 'dymanic_userlover'];
        $table = $tables[$type];
        if (!$table) return $this->miss('参数错误');
        if ($type == 1) {
            $ids = $this->db->name($table)->where(['userid'=>$this->member['id']])->column('dy_id');
            if ($ids) {
                $this->db->name('dymanic')->where(['dy_id'=>['in', $ids]])->setDec('lover');
                $res = $this->db->name($table)->where(['userid'=>$this->member['id']])->delete();
            } else {
                $res = true;
            }
        } else {
            $res = $this->db->name($table)->where(['userid'=>$this->member['id']])->delete();
        }
        return $res ? $this->pass('操作成功') : $this->miss('操作失败');
    }



    public function AttestationMemberWheres()
    {
        $config['where'][] = [
            'name'  => '性别',
            'key'   => 'sex',
            'option'=>['男'=>'男','女'=>'女']
        ];
        // $config['where'][] = [
        //     'name'  => '问诊方式',
        //     'key'   => 'channel',
        //     'option'=>['1'=>'图文问诊','2'=>'语音问诊','3'=>'视频问诊']
        // ];
        $config['where'][] = [
            'name'  => '价格区间',
            'key'   => 'price',
            'option'=>['1'=>'10-19','2'=>'20-29','3'=>'30-50','4'=>'50以上']
        ];
        $config['where'][] = [
            'name'  => '区域',
            'key'   => 'city',
            'option'=>['1'=>'不限','2'=>'同城']
        ];
        $config['order'] = [
            '0'=>'综合排序',
            '1'=>'价格从低到高',
            '2'=>'价格从高到低',
        ];
        return $this->pass($config);
    }
    public function AttestationMember($type = 0, $keyword = '', $page = 1, $pagesize = 20, $order = 0, $category = 0, $channel = 0, $price = 0, $sex = 0, $city = 0)
    {
        if ($pagesize > 20) {
            return $this->pass([]);
        }
        $map = ['u.delete_time'=>0, 'u.reg'=>1, 'u.role'=>0];
        if ($this->member['id']) {
            $blacklist = Blacklist::lists($this->member['id'], false, true);
            if ($blacklist) {
                $blacklist[] = $this->member['id'];
            } else {
                $blacklist = [$this->member['id']];
            }
            $map['u.id'] = ['not in', $blacklist];
        }
        $joinWay = 'inner';
        // if ($type == 0) {
        //     $joinWay = 'left';
        // } else {
            // $map['a.types'] = $type == 3 ? ['in', [1, 2]] : $type;
            $map['a.types'] = ['in', [1, 2]];
            $map['a.status'] = 1;
            // $map['u.register_datetime'] = ['>=', '2023-04-15 00:00:00'];
        // }
        if ($keyword) {
            $map['u.name|u.id'] = ['like', '%'.$keyword.'%'];
            $map['u.entertainment'] = 1;
        }
        if ($sex) {
            $map['u.sex'] = $sex;
        }
        if ($city == 2) {
            $map['u.city'] = $this->member['city'];
        }
        if ($category) {
            $map[] = ['exp', Db::raw('find_in_set('.$category.', a.category)')];
        }
        $channelChecked = '';
        if ($channel) {
            $chatoption = ['', '', 'voice_switch', 'video_switch'];
            $channelChecked = $chatoption[$channel];
            if ($channelChecked) {
                $map['c.' . $channelChecked] = 1;
            }
        }
        if ($price) {
            $priceoption = [[],[10,19],[20,29],[30,50],[50,9999]];
            if (sizeof($priceoption[$price])) {
                if ($channelChecked) {
                    $map['c.' . str_replace('switch', 'price', $channelChecked)] = ['between', $priceoption[$price]];
                } else {
                    $map['c.chat_price|c.voice_price|c.video_price'] = ['between', $priceoption[$price]];
                }
            }
        }
        $orders = ['a.id desc', 'c.chat_price asc', 'c.chat_price desc'];
        $order = $orders[$order];

        if ($pagesize < 10) {
            $order = Db::raw('rand()');
        }

        $data = Db::name('user_attestation')
            ->alias('a')
            ->join('user u', 'a.user_id=u.id')
            ->join('config_personal c', 'c.user_id=u.id', $joinWay)
            ->where($map)
            ->field('u.id,u.name,u.head_portrait, c.chat_price,c.voice_price,c.video_price,c.voice_switch,c.video_switch,u.auth_tag,u.city,u.age,u.sex,u.entertainment')
            ->page($page)
            ->limit($pagesize)
            ->group('u.id')
            ->order($order)
            // ->fetchSql(true)
            ->select();
        // print_r($data);exit;

        $attestation = Db::name('user_attestation')->where(['user_id'=>['in', array_column($data, 'id')], 'status'=>1])->column('category,hospital,occupation', 'user_id');
        $cates = Db::name('topic')->where(['id'=>['in', implode(',', array_column($attestation, 'category'))]])->column('name','id');

        $attention = Db::name('attention')->where(['user_id' => $this->member['id']])->column('to_user');
        foreach ($data as &$value) {
            $value['is_attention'] = in_array($value['id'], $attention);

            $value['attestation'] = $attestation[$value['id']] ?? false;
            if ($value['attestation']) {
                $value['attestation']['category_name'] = $cates[explode(',', $value['attestation']['category'])[0]] ?? '';
            }
            $value['experiences'] = [];
            $value['skilled'] = [];
            $value['institutional'] = false;
            $experiences = Db::name('user_attestation')->where(['user_id'=>$value['id'], 'status'=>1])->field('types,category,hospital')->select();
            if ($experiences) {
                $experiencesValue = implode(',', array_column($experiences, 'category'));
                $experiencesValue = Db::name('topic')->where(['id'=>['in', $experiencesValue]])->column('name','id');
                foreach ($experiences as $k => $v) {
                    $eps = explode(',', $v['category']);
                    foreach ($eps as $k2 => $v2) {
                        $value[$v['types'] == 1 ? 'skilled' : 'experiences'][] = $experiencesValue[$v2];
                        
                        if ($v['types'] == 4) {
                            $value['institutional'] = $v['hospital'];
                        }
                    }
                }
            }

            $value['fields'] = [];
            if ($value['attestation'] || $value['experiences']) {
                // $value['fields'][] = ['name'=>'用户评分', 'value'=>'5.0'];
                // $value['fields'][] = ['name'=>'帮助', 'value'=>'999'];
                // $value['fields'][] = ['name'=>'经验', 'value'=>'999'];
            }
            $value['chat_config'] = [
                'chat_price' => $value['chat_price'],
                'voice_price' => $value['voice_price'],
                'video_price' => $value['video_price'],
                'voice_switch' => $value['voice_switch'],
                'video_switch' => $value['video_switch'],
            ];

            if ($value['chat_config']) {
                if ($value['chat_config']['chat_price'] && $value['chat_config']['chat_price'] > 2) {
                    $value['chat_config']['chat_price'] = 2;
                }
                if ($value['chat_config']['voice_price'] && $value['chat_config']['voice_price'] > 15) {
                    $value['chat_config']['voice_price'] = 15;
                }
                if ($value['chat_config']['video_price'] && $value['chat_config']['video_price'] > 30) {
                    $value['chat_config']['video_price'] = 30;
                }
            }
            if ($this->member['id'] && $value['id'] < 30000000) {
                $overpayscale = 0;
                // 获取所有关联账号的总支付
                $overpayscale = UserIntimateService::Count($this->member['id'], $value['id'], true);
                if ($overpayscale) {
                    $chat_scale['scale'] = $overpayscale;
                } else {
                    $chat_scale = Db::name('limit_chat_price')->where($this->member['id']>$value['id'] ? 'user_id='.$value['id']. ' and another_id='. $this->member['id'] : 'user_id='.$this->member['id']. ' and another_id='. $value['id'])->find();
                }

                if ($chat_scale) {
                    $value['chat_config']['chat_price'] = isset($value['chat_config']['chat_price']) ? round($value['chat_config']['chat_price'] * $chat_scale['scale'] / 100, 2) : 0;
                    $value['chat_config']['voice_price'] = isset($value['chat_config']['voice_price']) ? round($value['chat_config']['voice_price'] * $chat_scale['scale'] / 100, 2) : 0;
                    $value['chat_config']['video_price'] = isset($value['chat_config']['video_price']) ? round($value['chat_config']['video_price'] * $chat_scale['scale'] / 100, 2) : 0;
                }
            }
            foreach ($value['chat_config'] as $key => $v) {
                unset($value[$key]);
            }
        }
        return $this->pass($data);
    }
    public function data()
    {
        $upd = [
            'user_id' => $this->member['id'],
            'view_num'=>0,
            'video_time'=>0,
            'collect'=>0,
            'thumbsup'=>0,
            'comment'=>0,
        ];

        $dydata = Db::name('dymanic')->where(['userid'=>$this->member['id']])->field('visit,thumbsup,comments,lover')->select();
        $dydata2 = $this->db->name('dymanic')->where(['userid'=>$this->member['id']])->field('visit,thumbsup,comments,lover')->select();
        $upd['view_num'] = array_sum(array_column($dydata, 'visit')) + array_sum(array_column($dydata2, 'visit'));
        $upd['thumbsup'] = array_sum(array_column($dydata, 'thumbsup')) + array_sum(array_column($dydata2, 'thumbsup'));
        $upd['comment'] = array_sum(array_column($dydata, 'comments')) + array_sum(array_column($dydata2, 'comments'));
        $upd['collect'] = array_sum(array_column($dydata, 'lover')) + array_sum(array_column($dydata2, 'lover'));

        return $this->pass($upd);
    }
    public function share($dy_id)
    {
        $userid = $this->member['id'];

        if ($userid && !cache('dyshare:'. $userid . ':dyid' . $dy_id)) {
            $data = $this->db->name('dymanic')->where(['shenhe'=>1])->find($dy_id);
            if (!$data) return false;
            $this->db->name('dymanic')
                ->where(['dy_id' => $dy_id])
                ->update([
                    'shares'  =>  Db::raw('shares+1'),
                    // 'liveness'  =>  _calculateHotScore($data['visit'], $data['comments'], $data['thumbsup'], ++$data['shares'])
                ]);
            $this->db->name('dymanic_share')->insert(['user_id'=>$userid, 'dy_id'=>$dy_id, 'time'=>time()]);
            cache('dyshare:'. $userid . ':dyid' . $dy_id, $dy_id, 60);
        }
        return $this->pass('success');
    }

    public function emergency()
    {
        $data = $this->db->name('emergency')->field('update_time,create_time', 'filter')->select();
        $data = _toTree($data);
        return $this->pass($data);
    }

    public function frontier($page = 1, $pagesize = 20)
    {
        $data = $this->db->name('dymanic')->where(['class'=>7, 'shenhe'=>1])->field('dy_id, title, content, sumbImage, masterimg, cover, video, addtime, addway')->page($page)->limit($pagesize)->select();
        foreach ($data as &$value) {
            if ($value['masterimg']) {
                $value['masterimg'] = explode(',', $value['masterimg']);
                foreach ($value['masterimg'] as &$v) {
                    $v = _ossUrl($value['addway'] < 2 ? 0 : 1) . $v;
                }
                $value['sumbImage'] = explode(',', $value['sumbImage']);
                foreach ($value['sumbImage'] as &$v) {
                    $v = _ossUrl($value['addway'] < 2 ? 0 : 1) . $v;
                }
            } else if (!$value['cover']) {
                $doc=new \DOMDocument('1.0', 'utf-8');
                $internalErrors = libxml_use_internal_errors(true);
                $doc->loadHTML($value['content']);
                libxml_use_internal_errors($internalErrors);
                $xpath = new \DOMXPath($doc);

                // 使用 XPath 查询所有图像元素
                $images = $xpath->query('//img');

                // 遍历图像元素并获取 src 属性值
                $value['masterimg'] = [];
                $value['sumbImage'] = [];
                foreach ($images as $image) {
                    $src = $image->getAttribute('src');
                    if (strpos($src, "http://") === false && strpos($src, "https://") === false) {
                        $src = str_replace('/disk/uploads/download/', _ossUrl(0) . '/disk/uploads/download/', $src);
                        $src = str_replace('/public/uploads/us', 'http://' . getenv('B_APP_URL') . '/public/uploads/us', $src);
                    }
                    $value['masterimg'][] = $src;
                    $value['sumbImage'][] = $src;
                }
            }
            $value['video'] = $value['video'] ? _ossUrl($value['addway'] < 2 ? 0 : 1) . $value['video'] : '';
            $value['cover'] = $value['cover'] ? _ossUrl($value['addway'] < 2 ? 0 : 1) . $value['cover'] : '';
            if ($value['content']) {
                $value['content'] = strip_tags(htmlspecialchars_decode($value['content']));
                $value['content'] = str_replace('\n', '', $value['content']);
                $value['content'] = str_replace('\r', '', $value['content']);
                $value['content'] = str_replace(' ', '', $value['content']);
                $value['content'] = preg_replace('/\s+/','', $value['content']);
                $value['content'] = mb_substr($value['content'], 0, 100);
            }
        }
        return $this->pass($data);
    }

    public function mealplan()
    {
        $data = $this->db->name('meal_plan')->order('sort desc, id asc')->field('sort,create_time,update_time','filter')->select();
        return $this->pass($data);
    }
    public function rank()
    {
        $data = $this->db->name('rank_experience')->field('type,user_id,value')->order('sort desc, value desc, id asc')->select();

        $list = [];

        $userinfos_a = Db::name('user')->where(['id'=>['in', array_column($data, 'user_id')]])->column('id,name,head_portrait');
        $userinfos_b = $this->db->name('user')->where(['id' => ['in', array_column($data, 'user_id')]])->column('id,name,head_portrait');
        $userstmp = array_merge($userinfos_a, $userinfos_b);
        $users = [];
        foreach ($userstmp as $value) {
            $value['head_portrait'] = _ossUrl($value['id'] > 30000000 ? 0 : 1) . $value['head_portrait'];
            $users[$value['id']] = $value;
        }

        $ranknames = ['1'=>'exp', '2'=>'help', '3'=>'major'];

        foreach ($data as $key => $value) {
            $value['value'] = floatval($value['value']);
            $value['userinfo'] = $users[$value['user_id']] ?? false;
            if (!isset($list[$ranknames[$value['type']]])) {
                $list[$ranknames[$value['type']]] = [];
            }
            $list[$ranknames[$value['type']]][] = $value;
        }
        return $this->pass($list);
    }


    public function topic($name = '', $page = 1, $pagesize = 20, $field = 0)
    {
        $where = ['is_rec'=>1];
        if ($name) {
            $where = ['name'=>['like', "%$name%"]];
        }
        if ($field) {
            $data = Db::name('topic')
                    ->where($where)
                    ->page($page)
                    ->limit($pagesize)
                    ->field('id,name')
                    ->order('count desc, is_rec desc, update_time desc, create_time desc')
                    ->select();
        } else {
            $data = Db::name('topic')
                    ->where($where)
                    ->page($page)
                    ->limit($pagesize)
                    ->order('count desc, is_rec desc, update_time desc, create_time desc')
                    ->column('name');
        }
        return $this->pass($data);
    }


    public function userLabel()
    {
        $data = ['shanchang'=>[],'jingli'=>[]];

        $label_ids = Db::name('user_attestation')->where(['user_id'=>$this->params['user_id'], 'status'=>1, 'types'=>1])->column('category');
        $label_ids = $label_ids ? implode(',', $label_ids) : '';
        if ($label_ids) {
            $data['shanchang'] = Db::name('topic')->field('id, name')->where(['id' => ['in', $label_ids]])->select();
        }

        $label_ids = Db::name('user_attestation')->where(['user_id'=>$this->params['user_id'], 'status'=>1, 'types'=>['in', [2,3]]])->column('category');
        $label_ids = $label_ids ? implode(',', $label_ids) : '';
        if ($label_ids) {
            $data['jingli'] = Db::name('topic')->field('id, name')->where(['id' => ['in', $label_ids]])->select();
        }

        return $this->pass($data);
    }
}